package com.xuecheng.content.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xuecheng.base.execption.XueChengPlusException;
import com.xuecheng.content.mapper.CourseBaseMapper;
import com.xuecheng.content.mapper.CourseCategoryMapper;
import com.xuecheng.content.mapper.CourseMarketMapper;
import com.xuecheng.content.model.dto.AddCourseDto;
import com.xuecheng.content.model.dto.CourseBaseInfoDto;
import com.xuecheng.content.model.dto.EditCourseDto;
import com.xuecheng.content.model.dto.QueryCourseParamsDto;
import com.xuecheng.content.model.po.CourseBase;
import com.xuecheng.content.model.po.CourseCategory;
import com.xuecheng.content.model.po.CourseMarket;
import com.xuecheng.content.service.CourseBaseInfoService;
import com.xuecheng.model.PageParams;
import com.xuecheng.model.PageResult;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

/**
 * @Author: chenheng
 * @Date: 2023/12/14 10:57
 */
@Service
public class CourseBaseInfoServiceImpl implements CourseBaseInfoService {
    @Autowired
    CourseBaseMapper courseBaseMapper;
    @Autowired
    CourseMarketMapper courseMarketMapper;
    @Autowired
    CourseCategoryMapper courseCategoryMapper;
    @Transactional
    @Override
    public PageResult<CourseBase> queryCourseBaseList(PageParams pageParams, QueryCourseParamsDto queryCourseParamsDto) {
        //设置分页  long current, long size
        Page<CourseBase> courseBasePage = new Page<>(pageParams.getPageNo(),pageParams.getPageSize());

        //设置查询条件
        LambdaQueryWrapper<CourseBase> queryWrapper = new LambdaQueryWrapper<>();
        //根据课程名称模糊查询  name like '%名称%'
        queryWrapper.like(StringUtils.isNotEmpty(queryCourseParamsDto.getCourseName()),CourseBase::getName,queryCourseParamsDto.getCourseName());
        //根据课程审核状态
        queryWrapper.eq(StringUtils.isNotEmpty(queryCourseParamsDto.getAuditStatus()),CourseBase::getAuditStatus,queryCourseParamsDto.getAuditStatus());
        //根据发布状态
        queryWrapper.eq(StringUtils.isNotEmpty(queryCourseParamsDto.getPublishStatus()),CourseBase::getStatus,queryCourseParamsDto.getPublishStatus());

        //测试查询接口  E page, @Param("ew") Wrapper<T> queryWrapper 结果为1个分页查询结果集合
        Page<CourseBase> courseBasePageResult = courseBaseMapper.selectPage(courseBasePage, queryWrapper);

        //设置返回结果集合
        List<CourseBase> items = courseBasePageResult.getRecords();
        long total = courseBasePageResult.getTotal();

        //封装结果集合 List<T> items, long counts, long page, long pageSize
        PageResult<CourseBase> courseBasePageResult1 = new PageResult<CourseBase>(items,total,pageParams.getPageNo(),pageParams.getPageSize());
        return courseBasePageResult1;
    }

    @Transactional
    @Override
    public CourseBaseInfoDto createCourseBase(Long companyId, AddCourseDto dto) {
        //合法校验
//        if (StringUtils.isBlank(dto.getName())){
//            throw new XueChengPlusException("课程名称为空");
//        }
//        if (StringUtils.isBlank(dto.getMt())) {
//            throw new XueChengPlusException("课程分类为空");
//        }
//
//        if (StringUtils.isBlank(dto.getSt())) {
//            throw new XueChengPlusException("课程分类为空");
//        }
//
//        if (StringUtils.isBlank(dto.getGrade())) {
//            throw new XueChengPlusException("课程等级为空");
//        }
//
//        if (StringUtils.isBlank(dto.getTeachmode())) {
//            throw new XueChengPlusException("教育模式为空");
//        }
//
//        if (StringUtils.isBlank(dto.getUsers())) {
//            throw new XueChengPlusException("适应人群为空");
//        }
//
//        if (StringUtils.isBlank(dto.getCharge())) {
//            throw new XueChengPlusException("收费规则为空");
//        }
        //新增对象
        CourseBase courseBase = new CourseBase();
        //将填写的课程基本信息赋值给新增的对象
        BeanUtils.copyProperties(dto,courseBase);
        //将courseBase中不为空的属性赋值
        courseBase.setCompanyId(companyId);
        //设置审核状态
        courseBase.setStatus("202002");
        //设置发布状态
        courseBase.setAuditStatus("203001");
        courseBase.setCreateDate(LocalDateTime.now());
        //向课程基本表插入数据
        int insert = courseBaseMapper.insert(courseBase);
        if (insert<=0){
            throw new RuntimeException("新增课程基本信息失败");
        }
        //向课程market插入数据
        //新增对象
        CourseMarket courseMarketNew = new CourseMarket();
        //将填写的课程基本信息赋值给新增的对象
        BeanUtils.copyProperties(dto,courseMarketNew);
        //设置主键，因为market与base表一对一关联
        courseMarketNew.setId(courseBase.getId());
        //调用插入函数
        int i = saveCourseMarket(courseMarketNew);
        if (i<=0){
            throw new XueChengPlusException("新增课程基本信息失败");
        }
        //查询课程基本信息以及market信息并封装返回
        CourseBaseInfoDto courseBaseInfoDto = getCourseBaseInfoDto(courseBase.getId());
        return courseBaseInfoDto;
    }
    private int saveCourseMarket(CourseMarket courseMarketNew){
        //合法性判断
        String charge = courseMarketNew.getCharge();
        if (StringUtils.isBlank(charge)){
            throw new XueChengPlusException("未选择收费规则");
        }
        if (charge.equals("201001")){
            if (courseMarketNew.getPrice().floatValue()<=0||courseMarketNew.getPrice()==null){
                XueChengPlusException.cast("课程价格必须大于0");
            }
        }
        //根据id从课程营销表查询
        CourseMarket courseMarket = courseMarketMapper.selectById(courseMarketNew.getId());
        if (courseMarket == null){
            return courseMarketMapper.insert(courseMarketNew);
        }else {
            BeanUtils.copyProperties(courseMarketNew,courseMarket);
            courseMarket.setId(courseMarketNew.getId());
            return courseMarketMapper.updateById(courseMarket);
        }
    }
    public CourseBaseInfoDto getCourseBaseInfoDto(Long id){
        CourseBaseInfoDto courseBaseInfoDtoNew = new CourseBaseInfoDto();
        //从base中查数据
        CourseBase courseBase = courseBaseMapper.selectById(id);
        if (courseBase==null){
            return null;
        }
        //从market中查询
        CourseMarket courseMarket = courseMarketMapper.selectById(id);
        BeanUtils.copyProperties(courseBase,courseBaseInfoDtoNew);
        if (courseMarket!=null){
            BeanUtils.copyProperties(courseMarket,courseBaseInfoDtoNew);
        }
        //查询分类名字
        CourseCategory courseCategory = courseCategoryMapper.selectById(courseBase.getMt());
        courseBaseInfoDtoNew.setMtName(courseCategory.getName());
        CourseCategory courseCategory1 = courseCategoryMapper.selectById(courseBase.getSt());
        courseBaseInfoDtoNew.setStName(courseCategory1.getName());
        return courseBaseInfoDtoNew;
    }

    @Override
    public CourseBaseInfoDto modifyCourseBase(Long companyId,EditCourseDto editCourseDto) {
        //合法性判断
        //课程id是否存在,公司id是否一致
        CourseBase courseBase = courseBaseMapper.selectById(editCourseDto.getId());
        if (courseBase == null){
            XueChengPlusException.cast("修改课程不存在");
        }
        if (!courseBase.getCompanyId().equals(companyId)){
            XueChengPlusException.cast("本机构只能修改本机构的课程");
        }
        //封装插入基本信息
        BeanUtils.copyProperties(editCourseDto,courseBase);
        courseBase.setChangeDate(LocalDateTime.now());
        courseBase.setChangePeople(courseBase.getCompanyName());
        courseBaseMapper.updateById(courseBase);

        CourseMarket courseMarket = new CourseMarket();
        BeanUtils.copyProperties(editCourseDto,courseMarket);
        saveCourseMarket(courseMarket);

        //返回修改后的课程基本信息

        CourseBaseInfoDto courseBaseInfoDto = getCourseBaseInfoDto(editCourseDto.getId());
        return courseBaseInfoDto;
    }
}
